import sys
import random

import pygame


class Bird(object):
    """
    定义一个鸟
    """

    def __init__(self):
        self.bird_rect = pygame.Rect(40, 30, 30, 30)
        self.bird_status = [
            pygame.image.load('../img/0.png'),
            pygame.image.load('../img/1.png'),
            pygame.image.load('../img/2.png'),
            pygame.image.load('../img/dead.png'),
        ]
        self.status = 0
        self.bird_x = 120
        self.bird_y = 300
        self.jump = False
        self.jump_speed = 5
        self.gravity = 5
        self.dead = False

    def bird_update(self):
        if self.jump:
            self.jump_speed -= 1
            self.bird_y -= self.jump_speed
            self.bird_x += 0.3

        else:
            self.gravity += 0.2
            self.bird_y += self.gravity
        self.bird_rect[1] = self.bird_y


class Pipeline(object):
    """定义一个管道类"""

    def __init__(self):
        """定义初始化方法"""
        self.wallx = 400  # 管道所在X轴坐标
        self.pineUp = pygame.image.load("../img/top.png")
        self.pineDown = pygame.image.load("../img/bottom.png")

    def update_pipeline(self):
        """"管道移动方法"""
        self.wallx -= 5  # 管道X轴坐标递减，即管道向左移动
        # 当管道运行到一定位置，即小鸟飞越管道，分数加1，并且重置管道
        if self.wallx < -80:
            global score
            score += 1
            self.wallx = 400


def create_map(top, bottom):
    """定义创建地图的方法"""
    screen.fill((255, 255, 255))  # 填充颜色
    screen.blit(background, (0, 0))  # 填入到背景

    # 显示管道
    screen.blit(Pipeline.pineUp, (Pipeline.wallx, top))  # 上管道坐标位置
    screen.blit(Pipeline.pineDown, (Pipeline.wallx, bottom))  # 下管道坐标位置
    Pipeline.update_pipeline()  # 管道移动

    # 显示小鸟
    if Bird.dead:  # 撞管道状态
        Bird.status = 3
    elif Bird.jump:  # 起飞状态
        Bird.status = 1
    screen.blit(Bird.bird_status[Bird.status], (Bird.bird_x, Bird.bird_y))  # 设置小鸟的坐标
    Bird.bird_update()  # 鸟移动

    # 显示分数
    screen.blit(font.render('Score:' + str(score), -1, (255, 255, 255)), (100, 50))  # 设置颜色及坐标位置
    pygame.display.update()  # 更新显示


def checkDead(top, bottom):
    # 上方管子的矩形位置
    upRect = pygame.Rect(Pipeline.wallx, top,
                         Pipeline.pineUp.get_width() - 10,
                         Pipeline.pineUp.get_height())

    # 下方管子的矩形位置
    downRect = pygame.Rect(Pipeline.wallx, bottom,
                           Pipeline.pineDown.get_width() - 10,
                           Pipeline.pineDown.get_height())
    # 检测小鸟与上下方管子是否碰撞
    if upRect.colliderect(Bird.bird_rect) or downRect.colliderect(Bird.bird_rect):
        Bird.dead = True
    # 检测小鸟是否飞出上下边界
    if not 0 < Bird.bird_rect[1] < height:
        Bird.dead = True
        return True
    else:
        return False


def getResutl():
    final_text1 = "Game Over"
    final_text2 = "click restart"
    ft1_font = pygame.font.SysFont("Arial", 70)  # 设置第一行文字字体
    ft1_surf = font.render(final_text1, 1, (242, 3, 36))  # 设置第一行文字颜色
    ft2_font = pygame.font.SysFont("Arial", 50)  # 设置第二行文字字体
    ft2_surf = font.render(final_text2, 1, (253, 177, 6))  # 设置第二行文字颜色
    screen.blit(ft1_surf, [screen.get_width() / 2 - ft1_surf.get_width() / 2, 100])  # 设置第一行文字显示位置
    screen.blit(ft2_surf, [screen.get_width() / 2 - ft2_surf.get_width() / 2, 200])  # 设置第二行文字显示位置
    pygame.display.flip()  # 更新整个待显示的Surface对象到屏幕上


def check_win(bird_x):
    if bird_x > 400:
        return True
    else:
        return False


def show_win():
    final_text1 = 'you WIN!!!'
    ft2_surf = font.render(final_text1, 1, (253, 177, 6))
    screen.blit(ft2_surf, [screen.get_width() / 2 - ft2_surf.get_width() / 2, 200])
    pygame.display.flip()  # 更新整个待显示的Surface对象到屏幕上


if __name__ == '__main__':
    """主程序"""
    pygame.init()  # 初始化pygame
    pygame.font.init()  # 初始化字体
    font = pygame.font.SysFont("Arial", 50)  # 设置字体和大小
    size = width, height = 400, 650  # 设置窗口
    screen = pygame.display.set_mode(size)  # 显示窗口
    clock = pygame.time.Clock()  # 设置时钟
    Pipeline = Pipeline()  # 实例化管道类
    Bird = Bird()  # 实例化鸟类
    score = 0
    top = -300
    bottom = 500
    while True:
        if checkDead(top, bottom):
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    score = 0
                    top = -300
                    bottom = 500
                    Pipeline.__init__()  # 实例化管道类
                    Bird.__init__()  # 实例化鸟类
        clock.tick(60)  # 每秒执行60次
        # 轮询事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if (event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN) and not Bird.dead:
                Bird.jump = True  # 跳跃
                Bird.gravity = 5  # 重力
                Bird.jump_speed = 10  # 跳跃速度
            if checkDead(top, bottom) and event.type == pygame.KEYDOWN:
                score = 0
                top = -300
                bottom = 500
                Pipeline.__init__()  # 实例化管道类
                Bird.__init__()  # 实例化鸟类

        background = pygame.image.load("../img/background.png")  # 加载背景图片
        # 当飞过一个柱子,初始化上下管子的位置
        if Pipeline.wallx == 400:
            top = -random.randint(150, 300)
            bottom = random.randint(350, 600)
        if checkDead(top, bottom):  # 检测小鸟生命状态
            getResutl()  # 如果小鸟死亡，显示游戏总分数
        elif check_win(Bird.bird_x):  # 检查小鸟是否获胜
            show_win()  # 如果小鸟获胜，显示获胜提示
        else:
            create_map(top, bottom)  # 创建地图
    pygame.quit()
